/*
Java source file
Copyright: Umschalt.com 2012
*/
package com.david.documentation.web.view.components;

import com.david.documentation.domain.entities.AutocompleteData;
import com.david.documentation.domain.entities.category.Category;
import com.david.documentation.domain.entities.tags.Tag;
import com.david.documentation.service.category.CategoryService;
import com.david.documentation.service.search.SearchService;
import com.david.documentation.service.tag.TagService;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteBehavior;
import org.apache.wicket.markup.html.form.FormComponent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AutocompleteDataBehavior extends AutoCompleteBehavior<AutocompleteData>{

	private SearchService searchService;
	private CategoryService categoryService;
	private TagService tagService;

	public static final String KATGEORY_VALUE = "Kategorie";
	public static final String TAG_VALUE = "Tag";
	

	public AutocompleteDataBehavior(FormComponent<?> component,SearchService searchService,
			CategoryService categoryService, TagService tagService) {
		super(new AutocompleteDataRenderer(component));
		this.searchService = searchService;
		this.categoryService = categoryService;
		this.tagService = tagService;
	}

	@Override
	protected Iterator<AutocompleteData> getChoices(String input) {

		List<AutocompleteData> tmp = new ArrayList<AutocompleteData>();

		if (!StringUtils.isEmpty(input)){

			tmp.addAll(searchService.findDokuNamesStringLimitSql(input,0,10));

			for (Category category : categoryService.findCategorysByName(input)){
				tmp.add(new AutocompleteData(category.getName(),KATGEORY_VALUE));
			}
			for (Tag tag : tagService.findTagsByName(input)){
				tmp.add(new AutocompleteData(tag.getName(),TAG_VALUE));
			}
		}
		if (tmp != null && tmp.size() > 0){
			return tmp.iterator();
		} else{
			return java.util.Collections.EMPTY_LIST.iterator();
		}
	}
}
